#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
# ----------------------------------------------------------------------------
#  Purpose:     用于实现XML文件读写

#  Author:      青衫少年春归也

#  Created:     2019.12.19

# ----------------------------------------------------------------------------
'''

from lxml import etree


class XMLParser():
    def parser_xml_file(self, _path:str) ->dict:
        """
        解析XML文件,根据对应节点生成字典
        参数值:
            :param _path: XML文件路径地址
        返回值:
            {
                "name":"",   节点名称
                "value":"",  节点值
                "attributes":{}, 节点的属性字典
                "children":[], 子节点信息
            }
        """
        data = {}
        xml = etree.parse(_path)
        root = xml.getroot()                                                         #   获取根节点
        root_name = root.tag                                                         #   获取根节点名称
        root_value = root.text.replace("\n", "").strip() if root.text else ""        #   获取根节点值
        root_attributes = {x[0]:x[1] for x in root.items()}                          #   获取根节点属性值
        data.update({"name":root_name, "value":root_value, "attributes":root_attributes, "children":[] })
        for node in root.getchildren():
            self._parser_xml_file_nodes(node, data["children"])
        return data


    def _parser_xml_file_nodes(self, node:etree.Element, data:list):
        """
        解析XML文件的子节点，并加入到字典中
        参数信息:
            :param node: XML节点对象
            :param data: 返回字典对象
        """
        single_node_info = {}
        node_name = node.tag
        node_value = node.text.replace("\n", "").strip() if node.text else ""
        node_attributes = {x[0]: x[1] for x in node.items()}
        single_node_info.update({"name": node_name, "value": node_value, "attributes": node_attributes, "children": []})
        data.append(single_node_info)
        for child in node.getchildren():
            self._parser_xml_file_nodes(child, single_node_info["children"])


